package wzj.mybatisplusdemo.web;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import wzj.mybatisplusdemo.po.Creation;
import wzj.mybatisplusdemo.po.User;
import wzj.mybatisplusdemo.service.CreationService;
import wzj.mybatisplusdemo.web.dto.RespEntity;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@CrossOrigin
@RestController
@RequestMapping("/creation")
public class CreationController {
    @Autowired
    private CreationService creationService;
    @Value("${my.img_dir}")
    private String imgDir = null;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping(value = "/all",produces = "application/json;charset=utf-8")
    public String all() {
        List<Creation> list = null;
        if(stringRedisTemplate.hasKey("creation_all")) {
            System.out.println("从redis里获取数据");
            return (String) stringRedisTemplate.opsForValue().get("creation_all");
        }
        list = creationService.list();
        System.out.println("从数据库里获取数据");
        RespEntity respEntity = new RespEntity("2000","查询成功", list);
        String json = JSON.toJSONString(respEntity);
        stringRedisTemplate.opsForValue().set("creation_all", json, 1, TimeUnit.MINUTES);
        return json;
    }

    // 获取创作详情（用于编辑）
    @GetMapping("/detail/{id}")
    public RespEntity detail(
            @PathVariable("id") Integer id) {

        Creation creation = creationService.getById(id);
        return new RespEntity("2000", "获取成功", creation);
    }

    @RequestMapping(value = "/list",produces = "application/json;charset=utf-8")
    public String list(
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum
            ,@RequestParam(value = "pageSize", defaultValue = "2") int pageSize
            ,@RequestParam(value = "search", defaultValue = "")String search) {
        String key = "creation_list_" + pageNum + "_" + pageSize;
        if(search.isEmpty() && stringRedisTemplate.hasKey(key)){
            return (String) stringRedisTemplate.opsForValue().get(key);
        }
        Page<Creation> page = new Page<>(pageNum, pageSize);
//        page.addOrder(OrderItem.desc("s_click"));
//        page.addOrder(OrderItem.asc("s_createtime"));
        QueryWrapper<Creation> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().like(!search.isEmpty(),Creation::getTitle, search)
                .or().like(!search.isEmpty(),Creation::getContent, search)
                .orderByDesc(Creation::getCreateTime)
                .orderByDesc(Creation::getCreateTime);


        creationService.page(page,queryWrapper);
        RespEntity respEntity = new RespEntity("2000","查询成功",page);
        String json = JSON.toJSONString(respEntity);
        if(search.isEmpty()){
            stringRedisTemplate.opsForValue().set(key, json, 10, TimeUnit.MINUTES);
        }
        return json;
    }
    @PostMapping("/publish")
    public RespEntity pulish(@RequestAttribute("curUser") User curUser,  HttpServletRequest request, Creation creation, MultipartFile pic, String ai_img_url) throws IOException {


        String dir=this.imgDir;
        File dirFile=new File(dir);
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        if(!ai_img_url.isEmpty()){
            String fileName=saveImageFromUrl(ai_img_url,dir);
            creation.setImg(fileName);
        }
        else if(!pic.isEmpty()){
            String fileName=new Date().getTime()+"_"+pic.getOriginalFilename();
            pic.transferTo(new File(dir+"\\"+ fileName));//把图片统一保存在某个目录
            creation.setImg(fileName);//把图片的路径保存到数据库去
        }
        creation.setUserId(curUser.getId());
        creation.setClick(0);
        creation.setCreateTime(new Date());
        creationService.save(creation);
        return new RespEntity("2000", "发布成功", creation);
    }
    public String saveImageFromUrl(String imageUrl, String dir) throws IOException {
        // 创建HttpClient实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建HTTP GET请求
        HttpGet httpGet = new HttpGet(imageUrl);
        // 执行请求
        CloseableHttpResponse response = httpClient.execute(httpGet);
        try {
            // 检查响应状态
            int statusCode = response.getStatusLine().getStatusCode();
            System.out.println("响应状态码: " + statusCode);

            if (statusCode >= 200 && statusCode < 300) {
                // 获取响应体
                HttpEntity entity = response.getEntity();
                byte[] imageBytes = EntityUtils.toByteArray(entity);
                // 生成文件名
                String fileName = new Date().getTime() + "_" + imageUrl.split("\\?")[0].substring(imageUrl.lastIndexOf("/") + 1);
                // 保存图片
                Path imagePath = Paths.get(dir, fileName);
                Files.write(imagePath, imageBytes);

                return fileName;
            }
            return null;
        } finally {
            // 关闭响应
            response.close();
            httpClient.close();
        }
    }

}
